package 数据结构.sparearray;

import java.io.FileOutputStream;
import java.io.IOException;

public class SparsArray {
    public static void main(String[] args) throws IOException {
        int[][] chessArr1 = new int[11][11];
        chessArr1[1][2] = 1;
        chessArr1[2][3] = 2;
        chessArr1[4][5] = 2;
        System.out.println("原始的二维数组");
        for (int[] row : chessArr1) {
            for (int data : row) {
                System.out.printf("%d\t", data);
            }
            System.out.println();
        }
        int sum = 0;

        for (int i = 0; i < 11; i++) {
            for (int i1 = 0; i1 < 11; i1++) {
                if (chessArr1[i][i1] != 0) {
                    sum++;
                }
            }
        }
        //创建稀疏数组
        int sparseArr[][] = new int[sum + 1][3];
        sparseArr[0][0] = 11;
        sparseArr[0][1] = 11;
        sparseArr[0][2] = sum;

        //遍历二维数组
        int count = 0;
        for (int i = 0; i < 11; i++) {
            for (int i1 = 0; i1 < 11; i1++) {
                if (chessArr1[i][i1] != 0) {
                    count++;
                    sparseArr[count][0] = i;
                    sparseArr[count][1] = i1;
                    sparseArr[count][2] = chessArr1[i][i1];
                }
            }
        }
        System.out.println();
        FileOutputStream fileOutputStream = new FileOutputStream("a.data");

        System.out.println("稀疏数组为=======");
        for (int i = 0; i < sparseArr.length; i++) {
            System.out.printf("%d\t%d\t%d\t\n", sparseArr[i][0], sparseArr[i][1], sparseArr[i][2]);
            String s = (sparseArr[i][0] + "," + sparseArr[i][1] + "," + sparseArr[i][2]) + "\r\n";
            byte[] bytes = s.getBytes();
            fileOutputStream.write(bytes);
            fileOutputStream.close();

        }

        //稀疏数组返回二维数组
        int chessArr2[][] = new int[sparseArr[0][1]][sparseArr[0][1]];
        System.out.println();
        System.out.println("恢复后的二维数组");

        for (int i = 1; i < sparseArr.length; i++) {
            chessArr2[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2];
        }
        for (int[] row : chessArr2) {
            for (int data : row) {
                System.out.printf("%d\t", data);
            }
            System.out.println();
        }
    }
}
